using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using schemas.microsoft.com.developer.msbuild.Item2003;
using System.IO;
using Xml.Schema.Linq;
using System.Xml.Linq;

namespace SetCommonConfigOnTargets
{
	public class TestProjectFilter : Filter
	{
		const String Pattern = "^.*\\\\(?<TargetName>[^\\\\]+)\\.TestProject[0-9]?\\.csproj$";
		#region Filter Members

		public bool Match(System.IO.FileInfo file)
		{
			return Regex.IsMatch(file.FullName, Pattern);
		}

		public TestProjectFilter()
		{
			BasePath = "";
		}
		public String BasePath
		{
			get;
			set;
		}

		public void Process(System.IO.FileInfo file)
		{
			bool modified = false;
			var project = Project.Load(file.FullName);
			var imports = project.Import;
			var importCommon = project.CommonImport;
			var genuilderPath = PathUtil.RelativePathTo(file.Directory.FullName, new FileInfo(BasePath + @"\Genuilder.dll").FullName);
			Reference genuilderReference = project.ItemGroup.SelectMany(g => g.Item).OfType<Reference>().FirstOrDefault(i => i.Include == "Genuilder");
			if(genuilderReference == null)
			{
				modified |= true;
				var itemGroupReferences = project.ItemGroup.First(g => g.Item.OfType<Reference>().Count() > 0);
				genuilderReference = new Reference();
				genuilderReference.Include = "Genuilder";
				var hintPath = new XElement("{http://schemas.microsoft.com/developer/msbuild/2003}HintPath");
				hintPath.Value = genuilderPath;
				genuilderReference.Untyped.Add(hintPath);
				itemGroupReferences.Item.Add(genuilderReference);
			}
			string toFile = BasePath + "/" + Regex.Match(file.FullName, Pattern).Groups["TargetName"].Value + ".targets";
			modified |= importCommon.EnsureHasImportToFile(toFile, file.Directory.FullName, Position.After);
			if(modified)
				project.Save(file.FullName);
		}

		#endregion
	}
}
